<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    /* * {
      padding: 0;
      margin: 0;
    } */
    .box {
      width: 300px;
      height: 100px;
      background-color: aqua;
      position: absolute;
      left: 50%;
      transform: translate(-50%);
      top: 100px;
    }
    .container {
      width: 100px;
      height: 2000px;
      background-color: gray;
    }
  </style>
  <body>
    <div class="container"></div>
    <div class="box"></div>
    <button class="btn">点击返回</button>
    <script>
      var boxEle = document.getElementsByClassName("box")[0];
      var btnEle = document.getElementsByClassName("btn")[0];
      window.onscroll = function () {
        var top = document.documentElement.scrollTop || document.body.scrollTop;
        console.log(top);
        if (top > 100) {
          boxEle.style.position = "fixed";
          boxEle.style.top = 0;
        } else {
          boxEle.style.position = "absolute";
          boxEle.style.top = "100px";
        }
        btnEle.onclick = function () {
          var top = document.documentElement.scrollTop;
          function setTop() {
            setTimeout(function () {
              top -= 100;
              document.documentElement.scrollTop = top;
              if (top > 0) {
                setTop();
              }
            }, 5);
          }
          setTop();
        };
      };
    </script>
  </body>
</html>
